from flask import request
import subprocess
import uuid
import urllib.parse
import json
from flask import jsonify
from flask import Flask
from flask_cors import CORS


app = Flask(__name__)
CORS(app)


@app.route('/kp/w3m/health', methods=['GET'])
def health_w3m_check():
    return "OK"


@app.route('/kp/w3m/html2text', methods=['POST'])
def html2text():
    html_data = request.data.decode()

    req = json.loads(html_data)
    file_uid = uuid.uuid4()

    file_name = '/root/w3m_tmp_files/tmp-html2text-' + str(file_uid) + '.html'

    with open(file_name, 'w', encoding='UTF-8') as file:
        file.write(urllib.parse.unquote(req['data']))

    with open("/usr/share/nginx/html/w3m/print_" + file_uid.__str__(), "w") as logfile:
        cp = subprocess.Popen(
            ['/usr/bin/w3m', '-I', 'UTF-8', '-O', 'GB18030', '-dump', file_name],
            stdout=logfile)

    res = {
        "url": 'http://47.117.162.39/w3m/print_' + file_uid.__str__()
    }

    return jsonify(res)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10012, debug=False)